/**
 * 新增编辑预约相关操作
 *
*/
import { orderFormList, getNeedCategoryList } from '@/api/select';
import { getCurrentZeroTime } from '@/utils';
import { selectTypeOptions } from '@/views/subcribe/model/selectData';
import { showModal } from '@/utils/message';

export default {
  data() {
    return {
      reservation: false,
      exclusive: false, // 排他存在竞品
      repeat: false, // 存在重复
      selectOptions: selectTypeOptions,
      orderFormList: [],
      orderValue: '',
      demandCategoryAry: [],
      maxHeight: ''
    };
  },
  computed: {
    formDataIsValid() {
      const { subcribeInfo: { id, dateTime, subscribeName }} = this;
      let isValid = true;
      if (this.$refs.subcribeRuleForm) {
        const { fields } = this.$refs.subcribeRuleForm;
        isValid = !fields.some(item => item.validateState === 'error');
      }
      return !!(id && dateTime && subscribeName && isValid);
    },
    ids() {
      return this.subcribeInfo.subscribeUserIds.map(res => {
        return res.id;
      });
    }
  },
  created() {
    this.needCategoryList();
  },
  methods: {
    nameBlur() {
      const str = this.subcribeInfo.subscribeName.replace(/(^\s*)|(\s*$)/g, '');
      this.subcribeInfo.subscribeName = str;
    },
    // 获取下单形式
    getFormList(orderPlatformId) {
      orderFormList(orderPlatformId).then((res) => {
        this.orderFormList = res.data;
        if (res.code === 500) {
          this.$message.error(res.message);
        }
      }).catch((err) => {
        console.log(err);
      });
    },
    // 获取品牌标签
    needCategoryList() {
      getNeedCategoryList().then(res => {
        this.demandCategoryAry = res.data;
        if (res.code === 500) {
          this.$message.error(res.message);
        }
      }).catch(err => {
        console.error(err);
      });
    },
    datePickerTime(value) {
      if (!value) {
        this.subcribeInfo.startDate = '';
        this.subcribeInfo.endDate = '';
      } else {
        this.subcribeInfo.startDate = Math.round(value[0]);
        this.subcribeInfo.endDate = Math.round(value[1]);
      }
    },
    exclusiveDatePickerTime(value) {
      if (!value) {
        this.subcribeInfo.exclusiveStartTime = '';
        this.subcribeInfo.exclusiveEndTime = '';
      } else {
        this.subcribeInfo.exclusiveStartTime = Math.round(value[0]);
        this.subcribeInfo.exclusiveEndTime = Math.round(value[1]);
      }
    },
    getParams(isEdit = false) {
      const subscribeUserIds = this.subcribeInfo.subscribeUserIds.map((item) => item.id);
      const {
        exclusiveEndTime,
        exclusiveStartTime,
        type,
        demandCategory,
        brandName,
        orderForm,
        subscribeName,
        version,
        startDate,
        endDate,
        remark
      } = this.subcribeInfo;
      const params = {
        exclusiveEndTime,
        exclusiveStartTime,
        type,
        orderForm,
        demandCategory,
        brandName,
        subscribeName,
        startDate: getCurrentZeroTime(startDate),
        endDate: getCurrentZeroTime(endDate, 1),
        remark,
        subscribeUserIds,
        reservation: this.reservation,
        exclusive: this.exclusive,
        repeat: this.repeat
      };
      if (this.subcribeInfo.orderForm && isEdit) {
        params.orderForm = this.subcribeInfo.orderForm;
      }
      if (isEdit) {
        params.version = version;
      } else {
        params.id = this.id;
      }
      return params;
    },
    resetInfo() {
      this.subcribeInfo = {
        id: '',
        subscribeName: '',
        startDate: '',
        endDate: '',
        remark: '',
        dateTime: '',
        brandName: '',
        type: '',
        orderForm: '',
        demandCategory: null,
        demandCategoryLabel: '',
        exclusiveDateTime: [],
        subscribeUserIds: []
      };
    },
    openDialogEvent(isEdit = false) {
      this.maxHeight = (window.innerHeight * 2) / 3;
      if (this.showMobilePage) this.maxHeight = this.maxHeight - 60;
      this.$nextTick(() => {
        this.$refs.subcribeRuleForm.resetFields();
      });
      this.accountNameOrganization = this.info.accountNameOrganization || '';
      this.resourceName = this.info.resourceName;
      this.subcribeInfo.id = this.info.id;
      this.id = this.info.id;
      if (isEdit && this.subcribeInfo.id) {
        this.subcribeInfo.version = this.info.version;
        this.getSubcribeDetail(this.subcribeInfo.id);
      } else {
        const selfUser = { id: this.userInfo.id, userName: this.userInfo.userName };
        this.subcribeInfo.subscribeUserIds.push(selfUser);
      }
    },
    closeDialog() {
      this.dialogVisible = false;
      this.resetInfo();
      this.id = '';
      this.isSubmit = false;
      this.reservation = false;
      this.exclusive = false;
      this.repeat = false;
      this.$refs.subcribeRuleForm.resetFields();
    },
    postMessage(data) {
      this.subcribeInfo.subscribeUserIds = data.relatedUserOptions;
    },
    // 提交请求后的提示
    checkDataStatus(res = {}, isEdit = false) {
      if (res.data) {
        const { data: { competeState }} = res;
        const isSubscribeDate = competeState === 1;
        if (competeState) {
          let msg = '';
          if (competeState === 3) {
            msg = `该账号相同的预约时间已有预约<br/>请确认是否继续预约？`;
          } else {
            msg = `该${isSubscribeDate ? '预约' : '排他'}时间内已有同类竞品<br/>请确认是否继续预约`;
          }
          showModal(msg, '', {
            confirmButtonText: '继续预约',
            cancelButtonText: competeState === 3 ? '查看预约' : '修改预约',
            dangerouslyUseHTMLString: true
          }, true).then(_ => {
            this.setStatus(competeState);
            this.handelOk();
          }).catch(_ => {
            if (competeState === 3) {
              this.$emit('openSubcribeListDialog', {
                resourceName: this.resourceName,
                dateTime: this.subcribeInfo.dateTime
              });
            }
          });
          return false;
        }
      }
      this.handleSuccess(isEdit);
    },
    setStatus(competeState) {
      switch (competeState) {
        // 存在预约竞品
        case 1: this.reservation = true;
          break;
        // 存在排他竞品
        case 2: this.exclusive = true;
          break;
        // 存在重复预约
        case 3: this.repeat = true;
          break;
      }
    },
    handleSuccess(isEdit = false) {
      this.$emit('success', this.info);
      this.dialogVisible = false;
      this.$message({ type: 'success', message: `${isEdit ? '编辑' : '新建'}成功` });
    }
  }
};
